package com.infinit.selfhelp.common.base

import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import androidx.activity.OnBackPressedCallback
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.LifecycleOwner
import com.infinit.selfhelp.common.R
import com.infinit.selfhelp.common.loading.CommonLoadingDelegate
import com.infinit.selfhelp.common.loading.LoadingDialogManager
import java.lang.Exception

abstract class BaseDialogFragment<B : ViewDataBinding> : DialogFragment(), LoadingDialogManager {
    val mBinding: B
        get() {
            return DataBindingUtil.bind(requireView())!!
        }


    override fun onCreate(savedInstanceState: Bundle?) {
        dialog?.window?.requestFeature(Window.FEATURE_NO_TITLE)
        dialog?.window?.addFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND)
        super.onCreate(savedInstanceState)
        initDataRequest()
        setStyle(STYLE_NO_TITLE, R.style.custom_dialog)
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        dialog?.window?.decorView?.setOnTouchListener { view, motionEvent ->
            if (motionEvent.action == MotionEvent.ACTION_DOWN) {
                hideKeyboard()
            }
            false
        }
        return initViews()
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        DataBindingUtil.bind<B>(view)
        initObserver()
        initListeners()
    }

    override fun onStop() {
        super.onStop()
        hideLoadingDialog()
    }

    open fun initDataRequest(){}
    open fun initObserver(){}
    abstract fun initViews(): View
    abstract fun initListeners()


    fun addOnBackPressed(
        owner: LifecycleOwner,
        onBackPressed: () -> Boolean,
    ): OnBackPressedCallback {
        val callback = object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                if (!onBackPressed()) {
                    isEnabled = false
                    requireActivity().onBackPressedDispatcher.onBackPressed()
                    isEnabled = true
                }
            }
        }
        requireActivity().onBackPressedDispatcher.addCallback(owner, callback)
        return callback
    }


    override val loadingDelegate by lazy { CommonLoadingDelegate() }


    override fun show(manager: FragmentManager, tag: String?) {
        try {
            val temp: FragmentManager? = null
            super.show(temp!!, tag)
        } catch (e: Exception) {
            val ft = manager.beginTransaction()
            ft.add(this, tag)
            ft.commitAllowingStateLoss()
        }
    }

    private fun hideKeyboard() {
        dialog?.currentFocus?.let {
            (requireContext().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).hideSoftInputFromWindow(it.windowToken, 0)
        }
    }
}
